#include "KDM2PrimaryGeneratorAction.hh"
#include "KDM2Globals.hh"
#include "G4Event.hh"
#include "G4PrimaryVertex.hh"
#include <fstream>
#include <iostream>
#include <iomanip>
#include <sstream>
using namespace std;

KDM2PrimaryGeneratorAction::KDM2PrimaryGeneratorAction(G4String eventFilePath, G4String kaonPosFilePath, int kaonCount) {
	numOfKaons = kaonCount;
	kaonPosList = new double*[numOfKaons];
	interface = new G4HEPEvtInterface(eventFilePath);

	ifstream kFile(kaonPosFilePath);
	int bufSize = 1024;
	char* buffer = new char[bufSize];
	for (int i = 0; i < numOfKaons; i++) {
		kaonPosList[i] = new double[3];
		for (int j = 0; j < 3; j++) {
			char delim = '\t';
			if (j == 2)
				delim = '\n';
			kFile.getline(buffer, bufSize, delim);
			kaonPosList[i][j] = atof(buffer);
		}
	}
	delete[] buffer;
	kFile.close();
	cout << endl;
}

KDM2PrimaryGeneratorAction::~KDM2PrimaryGeneratorAction() {
	delete interface;

	for (int i = 0; i < numOfKaons; i++)
		delete[] kaonPosList[i];
	delete[] kaonPosList;
}

void KDM2PrimaryGeneratorAction::GeneratePrimaries(G4Event* event) {
	eventNum++;
	int kaonNum = eventNum / maxPhotons;
	interface->SetParticlePosition(
			G4ThreeVector(kaonPosList[kaonNum][0], kaonPosList[kaonNum][1], kaonPosList[kaonNum][2]));
	interface->SetParticleTime(0);
	interface->GeneratePrimaryVertex(event);
	G4PrimaryParticle* particle = event->GetPrimaryVertex(0)->GetPrimary();
	photonEnergy = pow(pow(particle->GetPx(), 2) + pow(particle->GetPy(), 2) + pow(particle->GetPz(), 2), 0.5)
			* 299792458 * m / s;
	stringstream ss;
	ss.width(15);
	ss.fill('0');
	ss << left << ((double) eventNum) / numOfKaons / maxPhotons * 100;
	cout << "\r" << ss.str() << " % done" << flush;
}
